package tech.chauncy.springbootwebsample.util;

import org.yaml.snakeyaml.Yaml;
import tech.chauncy.springbootwebsample.entity.ProcessTestEntity;
import tech.chauncy.springbootwebsample.service.SnakeYaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class YamlUtil {

    private Map<String, ProcessTestEntity> map;

    public YamlUtil() throws FileNotFoundException {
        // TODO load all yaml files To Map
        map = new HashMap<>();
        Yaml yaml = new Yaml();

        String yamlPath = SnakeYaml.class.getClassLoader().getResource("yaml").getPath();
        ArrayList<File> yamlFiles = getFiles(yamlPath);
        for (File f : yamlFiles){
            if (f.isFile() && f!=null){
                String name = f.getName();
                String tel = f.getName().replace(".yaml","");
                System.out.println(name);
                ProcessTestEntity processSample = yaml.loadAs(new FileInputStream(f), ProcessTestEntity.class);
                map.put(tel, processSample);
            }
        }
    }

    //获取文件夹下文件列表
    public static ArrayList<File> getFiles(String path){
        ArrayList<File> fileList = new ArrayList<File>();
        File file = new File(path);
        if(file.isDirectory()){
            File []files = file.listFiles();
            for(File fileIndex:files){
                if(fileIndex.isDirectory()){
                    getFiles(fileIndex.getPath());
                }else if(fileIndex.isFile()){
                    fileList.add(fileIndex);
                }
            }
        }
        return fileList;
    }

    public ProcessTestEntity getById(String id){
        return map.get(id);
    }

}
